from lib import common
from db import db_handler

logger = common.get_logger('shop')


def add_to_cart_interface(username, product_info):
    """添加购物车接口"""
    userdata = db_handler.select(username)
    phone_name = product_info.get('name')
    phone_price = product_info.get('price')
    if phone_name not in userdata.get('shopping_cart'):
        userdata['shopping_cart'][phone_name] = {'price': phone_price, 'num': 1}
    else:
        userdata['shopping_cart'][phone_name]['num'] += 1
    db_handler.save(userdata)
    return userdata.get('shopping_cart')


def pay_interface(username):
    """清空购物车接口"""
    userdata = db_handler.select(username)
    balance = userdata.get('balance')
    shopping_cart = userdata.get('shopping_cart')
    s = 0
    for i in shopping_cart:
        s += shopping_cart[i]['price'] * shopping_cart[i]['num']
    if balance < s:
        prompt_msg = '用户[{}]的余额是[{:.2f}] 需要支付总额[{:.2f}] 支付失败'.format(username, balance, s)
        logger.debug(prompt_msg)
    else:
        userdata['balance'] -= s
        userdata['shopping_cart'].clear()
        db_handler.save(userdata)
        prompt_msg = '共支付[{:.2f}] 账户余额[{:.2f}] 支付成功'.format(s, balance - s)
        logger.info(prompt_msg)
    return prompt_msg
